package com.peza.bikelog.business.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.peza.bikelog.business.dao.BikelogDao;
import com.peza.bikelog.common.domain.LogEntry;

@Service("bikelogDao")
public class BikelogDaoImpl implements BikelogDao {

	@Autowired
	private EntityManager em;
	
	@Override
	public LogEntry getLogEntry(Long id) {
		return em.find(LogEntry.class, id);
	}
	
	@Transactional(propagation=Propagation.REQUIRED)
	public List<LogEntry> getLogEntryRange(long startIndex, long endIndex){
		List<LogEntry> entries = new ArrayList<LogEntry>();
		Query q2 = em.createQuery("from LogEntry L where L.id >= ? AND L.id <= ?");
		q2.setParameter(1, startIndex);
		q2.setParameter(2, endIndex);
		entries = q2.getResultList();
		
		return entries;
	}
	

	@Transactional(propagation=Propagation.REQUIRED)
	public void save(LogEntry le) {
		em.persist(le);
		
	}

	@Transactional(propagation=Propagation.REQUIRED)
	public void delete(Long id) {
		LogEntry le = getLogEntry(id);
		em.remove(le);
		
	}
}
